﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using CrossRoadNS.Model;

namespace CrossRoadNS.Services.Converters
{
    class CarVisualDirectionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Car car = value as Car;

            //if (car == null ||
            //    car.CrossRoad == null ||
            //    car.Route == null ||
            //    car.CurrentCell == null)
            //    return "e1";
            if (car==null)
            {
                return "e1";
            }
            if (car.CrossRoad == null)
            {
                return "e2";
            }
            if (car.Route==null)
            {
                return "e3";
            }
            if (car.CurrentCell==null)
            {
                return "e4";
            }

            int w = car.CrossRoad.width;
            int h = car.CrossRoad.height;

            var cc = new { X = car.CurrentCell.index % w, Y = car.CurrentCell.index / w };

            Cell nextCell = car.Route.Next(car.CurrentCell);
            if (nextCell == null)
            {
                if (cc.X == 0) return "l";
                if (cc.X == w-1) return "r";
                if (cc.Y == 0) return "u";
                if (cc.Y == h-1) return "d";
                return "e01";
            }

            var nc = new { X = nextCell.index % w, Y = nextCell.index / w };

            int visXdir = nc.X - cc.X;
            int visYdir = nc.Y - cc.Y;

            if (visXdir > 0) return "r";
            if (visXdir < 0) return "l";
            if (visYdir > 0) return "d";
            if (visYdir < 0) return "u";

            return "e02";
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
